﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.SqlServer.Server;
using System.Data.SqlClient;

namespace WorkerRole1
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            while (true)
            {                
                SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=DevelopmentStorageDb20090919;Integrated Security=SSPI;");
                SqlDataReader reader = null;
                DateTime createdDateTime;
                DateTime limitDateTime = DateTime.Now;
                limitDateTime = limitDateTime.AddHours(-1.0);
                SqlCommand selectCommand = new SqlCommand("select id, created from users", connection);
                SqlCommand deleteCommand = new SqlCommand();
                ArrayList IDs = new ArrayList();


                try 
                {
                    connection.Open();
                    reader = selectCommand.ExecuteReader();
                    
                    /*
                     * Cycle finds and saves expired user ids
                     */
                    while (reader.Read()) 
                    {
                        createdDateTime = DateTime.Parse(reader[1].ToString());
                        if (limitDateTime.CompareTo(createdDateTime) == 1) IDs.Add(reader[0].ToString());
                    }

                    if (reader != null) reader.Close();

                    /*
                     * Cycle deletes expired user from db
                     */
                    deleteCommand.Connection = connection;
                    foreach (string id in IDs)
                    {
                        deleteCommand.CommandText = "delete from users where id=" + id;
                        deleteCommand.ExecuteNonQuery();
                    }
                }
                finally 
                {
                    if (reader != null) reader.Close();
                    if (connection != null) connection.Close();
                }

                Thread.Sleep(1000 * 300); // time between 2 connections (5 min.)
            }
        }

        public override bool OnStart()
        {
            ServicePointManager.DefaultConnectionLimit = 12;           
            return base.OnStart();
        }
    }
}
